﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Threading;

using AKMII.DMRA.Common;
using AKMII.DMRA.Business.Management;
using AKMII.DMRA.Business.Service;

namespace AKMII.DMRA.Web
{
    public partial class ResetPassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDataList();
            }
        }

        private void BindDataList()
        {
            AccountManager am = new AccountManager();
            List<User> mds = am.GetUsers(UserType.MarketDirector);
            GridView1.DataSource = mds;
            GridView1.DataBind();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindDataList();
        }

        protected void btnCommit_Click(object sender, EventArgs e)
        {
            AccountManager am = new AccountManager();
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("chbReset");
                if (cb.Checked)
                {
                    string id = GridView1.Rows[i].Cells[1].Text;
                    string password = Utility.BuildPassword(8);

                    if (am.ResetUser(id, FormsAuthentication.HashPasswordForStoringInConfigFile(password, Constants.EncryptSetting)))
                    {
                        Mail mail = new Mail();
                        mail.Subject = "New password";
                        mail.Content = "Your password is reset to " + password;
                        mail.Recipients = new List<string>() { am.GetMailAddress(id) };

                        Thread thread = new Thread(new ParameterizedThreadStart(SendPassword));
                        thread.Start(mail);
                    }
                }
            }

            BindDataList();
        }

        protected void SendPassword(object o)
        {
            Mail mail = o as Mail;
            if (mail != null)
            {
                CommonUtility.SendMail(mail);
            }
        }
    }
}
